import { Button, Checkbox, Empty, Input, Message, Tooltip } from '@arco-design/web-react';
import { IconDoubleDown, IconDoubleUp, IconDown, IconUp } from '@arco-design/web-react/icon';
import { useEffect, useState } from 'react';
import LoadingMask from '../../../components/loadingMask';
import { IconEdit } from '../../../components/icon/svgIcon';
import { clearEmpty, clearRepeat, objectSortToString } from '../../../utils/utils';
import { apiGetCardDetailWalletRefundReason, apiUpdateCardDetailWalletRefundReasonDetail } from './api';
import CardDetailWalletRefundReasonDetailPage from './cardDetailWalletRefundReasonDetailPage';
import { CardDetailWalletRefundReason } from './types';
import DetailModal from '../../../components/detailModal';
interface Props {
  disabled?: boolean;
  valueInfos?: string;
  reasonType: string;
  onChange: (v?: string | number) => void;
  onCancel:() => void;
  onConfirm:(e:any) => void;
}
export default function RefundReasonList({ valueInfos, reasonType, disabled, onChange,onCancel,onConfirm }: Props) {

  let params = {
    orderByColumn: 'sortNum',
    isAsc: 'asc',
    status: 'enable',
    reasonType,
    pageNum: 1,
    pageSize: 1000
  };
  let paramsKey = objectSortToString({ pageNum: 1, pageSize: 1000, params });

  const [detailId, setDetailId] = useState<string | number | undefined>();
  const [searchValue, setSearchValue] = useState('');
  const [value, setvalue] = useState<string | undefined>(valueInfos);
  const [list, setlist] = useState<{ [x: string]: any }>({});
  //--------------------------------------------------------
  // 隐藏分类
  const [hideCat, setHideCat] = useState<string[]>([]);

  // 当前页需要的数据
  // const list = useSelector((state: AppStore) => state.cardDetailWalletRefundReasonList[paramsKey]);

  // 页面初始化时请求数据
  useEffect(() => {
    handleRefreshData();
  }, []); //eslint-disable-line

  async function handleRefreshData() {
    const res = await apiGetCardDetailWalletRefundReason(params)
    setlist({ results: res?.data?.rows })
  }

  // 修改 操作列内的修改
  function handleEdit(record?: CardDetailWalletRefundReason) {
    setDetailId(record?.id ?? 'create');
  }
  // 移动排序
  async function handleSort(record: CardDetailWalletRefundReason, swap?: CardDetailWalletRefundReason) {
    if (!swap) {
      Message.warning('首位或末位不可移动');
      return;
    }
    let body = Object.assign({}, record);
    let swapBody = Object.assign({}, swap);
    let t = body.sortNum;
    body.sortNum = swapBody.sortNum;
    swapBody.sortNum = t;
    try {
      LoadingMask.show('正在排序...');
      let res = await apiUpdateCardDetailWalletRefundReasonDetail((record.id ?? '')?.toString(), body);
      res = await apiUpdateCardDetailWalletRefundReasonDetail((swap.id ?? '')?.toString(), swapBody);
      let data = res.data;
      if (data.code === 200) {
        Message.success(data.msg ?? '排序成功');
        handleRefreshData();
        // dispatch(cardDetailWalletRefundReasonDetailRequest({ id: record.id!.toString(), forceRefresh: true }));
        // dispatch(cardDetailWalletRefundReasonDetailRequest({ id: swap.id!.toString(), forceRefresh: true }));
      } else {
        Message.warning(data.msg ?? '排序失败');
      }
    } catch (e: any) {
      Message.error(e.message ?? '排序失败');
    } finally {
      LoadingMask.hide();
    }
  }

  function handleChange(record: CardDetailWalletRefundReason) {
    let common = `${record.reasonClassify ?? '未分类'}:${record.name ?? ''}`;
    let _list = clearEmpty(clearRepeat((value ?? '').split(';')));
    if (_list.includes(common)) {
      _list.splice(_list.indexOf(common), 1);
    } else {
      _list.push(common);
    }
    setvalue(_list.join(';'))
    // onChange(_list.join(';'));
  }

  function handleHideCat(cat: string) {
    if (hideCat.includes(cat)) {
      setHideCat(hideCat.filter((i) => i !== cat));
    } else {
      setHideCat([...hideCat, cat]);
    }
  }

  function renderItem(i: CardDetailWalletRefundReason, idx: number) {
    let _list = catMap[i.reasonClassify ?? '未分类'];
    return (
      <div key={i.id} className="d-flex-r ai-center p-5">
        <Checkbox
          className="flex-1"
          disabled={disabled}
          checked={!!value && ((i.name ?? '').includes(value) || value.includes(i.name ?? ''))}
          onChange={() => handleChange(i)}
        >
          {i.name}
        </Checkbox>
        {!disabled && idx !== 0 && (
          // <HasPermission permission={['card:cardDetailWalletRefundReason:edit']}>
          <Tooltip content="排序靠前">
            <IconDoubleUp
              className="mr-5 text-primary-color cursor-pointer"
              onClick={() => handleSort(i, idx - 1 < 0 ? undefined : _list[idx - 1])}
            />
          </Tooltip>
          // </HasPermission>
        )}
        {!disabled && idx + 1 < _list.length ? (
          // <HasPermission permission={['card:cardDetailWalletRefundReason:edit']}>
          <Tooltip content="排序靠后">
            <IconDoubleDown
              className="mr-5 text-primary-color cursor-pointer"
              onClick={() => handleSort(i, idx + 1 >= _list.length ? undefined : _list[idx + 1])}
            />
          </Tooltip>
          // </HasPermission>
        ) : (
          <div className="w-18" />
        )}
        {!disabled && (
          // <HasPermission permission={['card:cardDetailWalletRefundReason:edit']}>
          <Tooltip content="编辑">
            <IconEdit className="text-primary-color" onClick={() => handleEdit(i)} />
          </Tooltip>
          // </HasPermission>
        )}
      </div>
    );
  }

  let _list = list?.results ?? [];
  if (searchValue) {
    _list = (list?.results ?? []).filter(
      (i: any) => (i.name ?? '').includes(searchValue) || (i.reasonClassify ?? '').includes(searchValue)
    );
  }
  if (disabled) {
    _list = _list.filter((i: any) => !!value && ((i.name ?? '').includes(value) || value.includes(i.name ?? '')));
  }

  let catMap: { [x: string]: CardDetailWalletRefundReason[] } = {};

  _list.forEach((i: any) => {
    if (!catMap[i.reasonClassify ?? '未分类']) {
      catMap[i.reasonClassify ?? '未分类'] = [];
    }
    catMap[i.reasonClassify ?? '未分类'].push(i);
  });

  return (
    <DetailModal
      className="bw-80"
      contentClassName="h-450"
      show
      title="退款申请"
      confirmBtnShow={true}
      cancelText="关闭"
      onConfirm={()=>{
        onConfirm(value)
      }}
      onCancel={()=>{
        onCancel()
      }}
      confirmText="确定"
    >
      <div className="bw-100  border border-radius-4 refund-reason-list">
        <div className="d-flex-r pl-10 pr-5 pt-10 pb-10">
          <div className="flex-1">退款原因</div>
          {!disabled && (
            // <HasPermission permission={['card:cardDetailWalletRefundReason:add']}>
            <Button type="primary" size="mini" onClick={() => handleEdit()}>
              新增
            </Button>
            // </HasPermission>
          )}
        </div>
        <div className="p-5">
          <Input placeholder="搜索原因/分类" onChange={(v) => setSearchValue(v)} />
        </div>
        <div className="h-600 scroll-bar-h-min ">
          {!list && <Empty />}
          {list?.fetching && !list?.loaded && <Empty description="正在获取..." />}
          {!list?.fetching && list?.loaded && !!list?.error && <Empty description={list.error} />}
          {Object.keys(catMap).map((cat) => (
            <div key={cat}>
              <div className="d-flex-r ai-center p-10 border-top" onClick={() => handleHideCat(cat)}>
                {hideCat.includes(cat) ? <IconUp /> : <IconDown />}
                <div className="flex-1 cursor-pointer">{cat}</div>
              </div>
              {!hideCat.includes(cat) &&
                catMap[cat].map((i, idx) => {
                  return renderItem(i, idx);
                })}
            </div>
          ))}
          {detailId && (
          <CardDetailWalletRefundReasonDetailPage
            id={detailId.toString()}
            reasonType={reasonType}
            onCancel={(v?: boolean) => {
              setDetailId(undefined);
              if (v) {
                handleRefreshData();
              }
            }}
          />
        )}
        </div>
      </div>
    </DetailModal>

  );
}
